<template>
  <div class="app-container">
    <div class="Header">
      <edit-form ref="filterContainer" v-show="showSearch" :editFormMap="filterMap" :editFormData="queryParams">
        <template slot="buttonGroup">
          <el-col :span="4">
            <el-form-item class="buttonGroup">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </template>
      </edit-form>
      <handle-button-group
        :showSearch.sync="showSearch"
        :single="single"
        :multiple="multiple"
        :authModule="{ module: 'question', name: 'zhQuest' }"
        @handleAdd="handleAdd"
        @handleUpdate="handleUpdate"
        @handleDelete="handleDelete"
        @handleExport="handleExport"
        @getList="getList"
      />
    </div>
    <table-list
      ref="tableListContainer"
      :tableListMap="tableMap"
      :request="{
        apiKey: 'ZhQuestList',
        params: { ...queryParams, groupId },
        method: 'get',
      }"
      :tableHeight="500"
      @selection-change="handleSelectionChange"
      @changeTableListAction="
        (TableList) => {
          userList = TableList;
        }
      "
    >
      <template slot="hasSelect">
        <el-table-column type="selection" width="55" :align="'center'" />
      </template>
      <template slot="hasHandle">
        <el-table-column label="操作" :align="'center'">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleSet(scope.row)" v-hasPermi="['question:zh:set']">设置为第一题</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['question:zh:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['question:zh:remove']">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </table-list>
    <!-- 添加或修改组合题对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      top="0vh"
      width="1200px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-button type="primary" @click="addZhBtn">添加更多</el-button>
      <div v-for="(item, index) in paramsList" :key="index" :style="{ borderTop: index !== 0 ? '1px solid #c0c4cc' : 'inherit' }">
        <h2>{{ type === 'add' ? '题目' + (index + 1) : '组合题' }}</h2>
        <!-- 基础题目 -->
        <basicQuest
          :ref="'basicQuest' + (index + 1)"
          :basicForm="item.basicForm"
          :questionDirect="item.questionDirect"
          @changeBasicData="(val) => answerOptionChange(val, { name: 'basicForm', index })"
          @changeDirect="(val) => answerOptionChange(val, { name: 'questionDirect', index })"
        ></basicQuest>
        <!-- 答题选项 -->
        <answerOption
          :ref="'answerOption' + (index + 1)"
          :optionList="item.optionList"
          @changeOptionList="(val) => answerOptionChange(val, { name: 'optionList', index })"
          type="zh"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import basicQuest from '../components/basicQuest';
import answerOption from '../components/answerOption';
import { addZh, updateZh, delZh, exportZh, getZh, setZh } from '@/api/question/zh';
import { getDataSource } from '@/static/js/dataSource';
import cloneDeep from 'lodash/cloneDeep';
import lodash from 'lodash';
export default {
  name: 'Zh',
  components: {
    basicQuest,
    answerOption,
  },
  props: {
    groupId: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    filterMap() {
      return getDataSource('editForm', 'questFilterMap');
    },
    tableMap() {
      return getDataSource('tableColumn', 'questTableMap');
    },
  },
  data() {
    return {
      optionListMap: {},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      userList: [],
      // 下拉数据对象
      tableOptionMap: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      type: 'add',
      // 查询参数
      queryParams: {},

      // 表单参数
      basicForm: {},
      // 定向答题
      questionDirect: {},
      // 答题选项
      optionList: [],
      params: {
        basicForm: {},
        questionDirect: {},
        optionList: [],
      },
      list: [],
      paramsList: [],
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.tableListContainer.init();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.$nextTick(() => {
        this.basicForm = this.$options.data().basicForm;
        this.questionDirect = this.$options.data().questionDirect;
        this.optionList = this.$options.data().optionList;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      const tableListContainer = this.$refs.tableListContainer;
      tableListContainer.pagination = tableListContainer.$options.data().pagination;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const filterContainer = this.$refs.filterContainer;
      filterContainer.resetForm('editFormData');
      this.handleQuery();
    },
    addZhBtn() {
      const params = this.$options.data().params;
      this.paramsList.push((Object.assign({}, params, { specifiedRange: 0, matchSwitch: 0 })));
      this.list.push(params);
    },
    answerOptionChange: lodash.debounce(
      function (val, { name, index }) {
        this.$set(this.list[index], name, val);
      },
      { maxWait: 1000 },
    ),
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.type = 'add';
      this.paramsList = [];
      this.list = [];
      this.addZhBtn();
      this.reset();
      this.title = '添加组合题';
      this.open = true;
    },
    /** 设置为第一题按钮操作 */
    handleSet(row) {
      setZh(row.id).then(() => {
        this.$message.success('设置成功');
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate({ id }) {
      this.type = 'edit';
      getZh(id).then((res) => {
        this.title = '修改组合题';
        this.open = true;
        const data = res.data;
        Object.keys(data).map((key) => {
          const keyArr = ['themeIds'];
          const fieldArr = ['themeId'];
          if (['questionDirectResp', 'optionList'].includes(key)) {
            const dataMap = {
              questionDirectResp: 'questionDirect',
              optionList: 'optionList',
            };
            this[dataMap[key]] = data[key];
            this.params[dataMap[key]] = data[key];
          } else if (data[key] && keyArr.includes(key)) {
            const index = keyArr.findIndex((item) => item === key);
            const valueArr = data[key].split(',').map((item) => parseInt(item));
            this.$set(this.basicForm, fieldArr[index], valueArr);
            this.$set(this.params.basicForm, fieldArr[index], valueArr);
            this.$set(this.basicForm, key, data[key]);
            this.$set(this.params.basicForm, key, data[key]);
          } else {
            this.$set(this.basicForm, key, data[key]);
            this.$set(this.params.basicForm, key, data[key]);
          }
        });
        this.paramsList.push(Object.assign({}, this.params, { specifiedRange: 0, matchSwitch: 0 }));
        this.list.push(this.params);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? row.id : this.ids.join(',');
      this.$modal
        .confirm('是否确认删除Id编号为"' + ids + '"的数据项？')
        .then(function () {
          return delZh(ids);
        })
        .then(() => {
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const tableListContainer = this.$refs.tableListContainer;
      const pagination = tableListContainer.pagination;
      const params = {
        ...pagination,
        ...this.queryParams,
      };
      exportZh(params, '组合题数据导出');
    },
    changeAction(prop) {},
    /** 提交按钮 */
    submitForm() {
      let optionFlag = true;
      this.list.some((item, index) => {
        if (!item.optionList.length) return this.$message.error('题目' + (index + 1) + '答题选项不能为空');
        return item.optionList.some((item, index) => {
          if (!item.optionTitle) {
            optionFlag = false;
            return this.$message.error(`第${index + 1}行的选项名称不能为空`);
          }
        });
      });
      if (!optionFlag) return;

      let validFlag = true;
      this.list.some((item, index) => {
        const basicQuest = this.$refs['basicQuest' + (index + 1)][0];
        const basicQuestContainer = basicQuest.$refs.basicQuestContainer;
        basicQuestContainer.$refs.editFormData.validate((basicValid) => {
          if (basicValid && validFlag) {
            if (index === this.list.length - 1) {
              const list = this.list.map((item) => {
                return {
                  ...item.basicForm,
                  optionList: item.optionList,
                  questionDirect: item.questionDirect,
                };
              });
              const params = cloneDeep({
                groupId: this.groupId,
                list,
              });
              if (this.type === 'edit') {
                updateZh(params).then(() => {
                  this.$message.success('修改成功');
                  this.reset();
                  this.getList();
                  this.open = false;
                });
              } else {
                addZh(params).then(() => {
                  this.$message.success('新增成功');
                  this.open = false;
                  this.getList();
                });
              }
            }
          }
          if (!basicValid) validFlag = false;
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
